package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class UploadController {


    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.上传文件的名字  全球唯一
        //2.上传路径
        //3.保存上传的图片位置
        String filename = file.getOriginalFilename();//获得上传的文件名字
        //文件名字改良一下
        //获得文件的后缀名
        filename = filename.substring(filename.lastIndexOf("."));
        //拼接名字
        String name = UUID.randomUUID().toString().replace("-", "");
        //创建新文件名字
        filename = name + filename;


        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++");
        System.out.println("新文件名字:"+filename);  //file

        //1.创建一个文件夹 .\\ 本级目录  ..\\ 上级目录
        File file1 = new File(path);
        if(!file1.exists()){
            //如果文件夹不存在，那么我们需要创建一个文件夹存放图片
            file1.mkdirs();//创建文件夹
        }
        //把文件写入到指定的位置 file1+filename  必须写绝对路径
        //如果想写入到项目的当前路径，那么请使用FileOutPutStream
        file.transferTo(new File(path+filename));
        //虚拟路径

        return R.success(filename);
    }


    /**
     * 文件下载
     * @param name  ba23a44966cc4668bd11fcb108340794.jpg
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //返回给前端的是一个图片
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/newupload")
    public R upload1(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.上传文件的名字  全球唯一
        //2.上传路径
        //3.保存上传的图片位置
        String filename = file.getOriginalFilename();//获得上传的文件名字
        //文件名字改良一下
        //获得文件的后缀名
        filename = filename.substring(filename.lastIndexOf("."));
        //拼接名字
        String name = UUID.randomUUID().toString().replace("-", "");
        //创建新文件名字
        filename = name + filename;
        System.out.println("新文件名字:"+filename);  //file

        // 当前项目在web服务器上的部署的绝对路径,也可以自己定义一个路径
        String serverBasePath = System.getProperty("user.dir");
        String serverFileSavePath = "/src/main/resources/backend/uploadfiles/";
        // 完整的服务器保存路径为 serverBasePath+ serverFileSavePath
        String serverSavePath = serverBasePath + serverFileSavePath;
        System.out.println(serverSavePath);

        //1.创建一个文件夹 .\\ 本级目录  ..\\ 上级目录
        File file1 = new File(serverSavePath);
        if(!file1.exists()){
            //如果文件夹不存在，那么我们需要创建一个文件夹存放图片
            file1.mkdirs();//创建文件夹
        }
        //把文件写入到指定的位置 file1+filename  必须写绝对路径
        //如果想写入到项目的当前路径，那么请使用FileOutPutStream
        file.transferTo(new File(serverSavePath+filename));
        //虚拟路径
        String str ="/backend/uploadfiles/";

        return R.success(str + filename);
    }

}
